﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;

namespace MouseExtender.Logic.Helpers
{
	public static class ProcessHelper
	{
		public static Process[] GetCurrentUserProcesses()
		{
			Process[] process = Process.GetProcesses();
			Func<Process, bool> userProcessSelector = new Func<Process, bool>(CheckIfUserProcess);
			var userProcesses = process.Where(userProcessSelector).Distinct(new ProcessEqualityComparer());
			return userProcesses.ToArray();
		}

		private static bool CheckIfUserProcess(Process process)
		{
			if (process.MainWindowHandle == IntPtr.Zero)
				return false;

			string mainModuleFileName = string.Empty;
			try
			{
				mainModuleFileName = process.MainModule.FileName;
			}
			catch (Win32Exception e)
			{
				// issue when running ME as different user
				if (e.NativeErrorCode == 5)
					return false;
				else
					throw e;
			}
			return !mainModuleFileName.Contains(Environment.SystemDirectory);
		}


		private class ProcessEqualityComparer : IEqualityComparer<Process>
		{

			#region IEqualityComparer<Process> Members

			public bool Equals(Process process, Process otherProcess)
			{
				string processName = process.MainModule.FileName;
				string otherProcessName = process.MainModule.FileName;
				return processName == otherProcessName;
			}

			public int GetHashCode(Process proc)
			{
				return proc.MainModule.FileName.GetHashCode();
			}

			#endregion
		}
	}
}
